package com.ruoyi.project.product.product.controller;

import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.product.product.domain.Product;
import com.ruoyi.project.product.product.service.IProductService;
import com.ruoyi.project.product.sku.domain.ProductSku;
import com.ruoyi.project.product.sku.service.IProductSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品Controller
 * 
 * @author ruoyi
 * @date 2024-04-20
 */
@RestController
@CrossOrigin
@RequestMapping("/product/product/api")
public class ProductApiController extends BaseController
{
    @Autowired
    private IProductService productService;

    @Autowired
    private IProductSkuService productSkuService;


    /**
     * 查询商品列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Product scProduct)
    {
        scProduct.setShelfStatus("是");
        startPage();
        List<Product> list = productService.userSelectProductList(scProduct);
        for(Product item: list){
            Long id = item.getId();
            ProductSku scProductSku = new ProductSku();
            scProductSku.setProductId(id);
            scProductSku.setIsReveal("是");
            List<ProductSku> scProductSkus = productSkuService.userSelectProductSkuList(scProductSku);
            // 按照 fieldName 字段升序排序
            List<ProductSku> sortedScProductSkus = scProductSkus.stream()
                    .sorted(Comparator.comparing(ProductSku::getPrice))
                    .collect(Collectors.toList());

            // 更新 item 的 skuList
            item.setSkuList(sortedScProductSkus);
        }
        return getDataTable(list);
    }

    /**
     * 查询商品列表
     */
    @GetMapping("/detail")
    public AjaxResult detail(Product product)
    {
        //校验商品id
        Long id1 = product.getId();
        if(id1 == null){
            return AjaxResult.error("参数校验失败");
        }

        Product item = productService.userSelectProductById(product.getId());
        return AjaxResult.success(item);
    }
}
